﻿<%@ WebHandler Language="C#" Class="StockReturnApplyBillHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

//Description:退库单处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:longb
//create Date:2025-09-28
public class StockReturnApplyBillHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSMfgOrderIBusiness m_MfgOrderObj = uMESBusinessFactory.instance.GetuLMSMfgOrderObject();
    private string toAppID_WMS = System.Configuration.ConfigurationManager.AppSettings["ToAppID_WMS"].ToString(); //推送给数据中心目标地址（WMS）
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetOrderList"://订单查询
                    GetOrderList(context);
                    break;
                case "saveStockReturnBillData"://保存退库申请单信息
                    saveStockReturnBillData(context);
                    break;
                case "getStockReturnApplyData"://查询退库申请单信息
                    getStockReturnApplyData(context);
                    break;
                case "getStockReturnApplyDataByPageSize"://查询退库申请单信息(分页)
                    getStockReturnApplyDataByPageSize(context);
                    break;
                case "updateStockReturnBillData"://更新退库申请单信息
                    updateStockReturnBillData(context);
                    break;
                case "deleteStockReturnBillData"://删除退库申请单信息
                    deleteStockReturnBillData(context);
                    break;
                case"GetMfgMaterial"://查询订单下的物料信息
                    GetMfgMaterial(context);
                    break;
                case "GetWmsMaterialBatch"://查询wms订单物料批次信息
                    GetWmsMaterialBatch(context);
                    break;    
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    public void GetOrderList(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();

        var sql = @"SELECT m.MFGORDERID,m.MFGORDERNAME,ot.ordertypename,u.ATTRIBUTEVALUE MachineNO,u1.ATTRIBUTEVALUE mfgYpe 
                ,PB.PRODUCTNAME,P.DESCRIPTION PRODUCTDESCRIPTION,to_char(m.PLANNEDSTARTDATE ,'yyyy-MM-dd')PLANNEDSTARTDATE ,to_char(m.PLANNEDCOMPLETIONDATE,'yyyy-MM-dd') PLANNEDCOMPLETIONDATE
                ,m.productfamilyname
                FROM MFGORDER m 
                LEFT JOIN Ordertype ot on ot.ordertypeid=m.ordertypeid
                LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
                LEFT JOIN USERATTRIBUTE u1 ON u1.PARENTID =m.MFGORDERID AND u1.USERATTRIBUTENAME ='订单类别'
                LEFT JOIN PRODUCT P  ON P.PRODUCTID = GET_SPLIT_MFGORDER_PRODUCTID(m.mfgorderid) 
                LEFT JOIN PRODUCTBASE PB  ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                LEFT JOIN WORKFLOW W  ON W.WORKFLOWID =P.WORKFLOWID 
                WHERE m.QTY>0";
        sql += " AND m.FACTORYID='" + m_UserInfo.FactoryID + "'";
        if (!string.IsNullOrWhiteSpace(para["mfgOrderName"]))
        {
            sql += " AND m.MFGORDERNAME LIKE '%" + para["mfgOrderName"] + "%'";
        }
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = sql;
        result = DatabaseHelper.RunProcedureForPage(paraPage);

        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存退库申请单信息
    /// </summary>
    /// <param name="context"></param>
    public void saveStockReturnBillData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var mfgOrderID = context.Request["mfgOrderID"].ToString();
        var sqlArr = new ArrayList();
        var dtCount = DatabaseHelper.Query_ReturnDatTable("select COUNT(distinct STOCKRETURNAPPLYBILLNO)+1 C From StockReturnApplyBill");
        var strSequence = "000000" + (dtCount.Rows.Count == 0 || dtCount.Rows[0]["C"].ToString() == "0" ? "1" : dtCount.Rows[0]["C"].ToString());
        var BillNo = "TKSQ-" + DateTime.Now.ToString("yyyy") + "-" + m_UserInfo.FactoryCode + "-" + strSequence.Substring(strSequence.Length - 4);
        var insertSQL = @"insert into StockReturnApplyBill(STOCKRETURNAPPLYBILLID,STOCKRETURNAPPLYBILLNO,STOCKRETURNTYPE,MFGORDERID,PRODUCTID,PRODUCTBATCHNO,STOCKRETURNNUM,STOCKRETURNREASON,CREATEDATE,CREATEEMPLOYEEID,STATUS,INSTORELOCATION, WAREHOUSECODE,CHECKSTATUS)
                        VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',sysdate,'{8}','0','{9}','{10}','0')";
        var updateSQL = @"update StockReturnApplyBill set PRODUCTBATCHNO='{1}',STOCKRETURNNUM='{2}',STOCKRETURNREASON='{3}',INSTORELOCATION='{4}', WAREHOUSECODE='{5}' where STOCKRETURNAPPLYBILLID='{0}'";
        foreach (DataRow row in dt.Rows)
        {
            if (dt.Columns.Contains("STOCKRETURNAPPLYBILLID") && !string.IsNullOrWhiteSpace(row["STOCKRETURNAPPLYBILLID"].ToString()))
            {
                sqlArr.Add(string.Format(updateSQL,row["STOCKRETURNAPPLYBILLID"].ToString(),row["PRODUCTBATCHNO"], row["STOCKRETURNNUM"], row["STOCKRETURNREASON"], row["STOCKRETURNREASON"], row["INSTORELOCATION"], row["WAREHOUSECODE"]));
            }
            else
            {
                var GID = Guid.NewGuid().ToString();
                sqlArr.Add(string.Format(insertSQL, GID, BillNo, row["STOCKRETURNTYPE"], mfgOrderID, row["PRODUCTID"], row["PRODUCTBATCHNO"], row["STOCKRETURNNUM"], row["STOCKRETURNREASON"], m_UserInfo.EmployeeID, row["INSTORELOCATION"], row["WAREHOUSECODE"]));
            }
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询退库申请单信息
    /// </summary>
    public void getStockReturnApplyDataByPageSize(HttpContext context)
    {
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var SelSQL = GetStockReturnApplySql(context);
        if (!string.IsNullOrWhiteSpace(dic["MfgOrdername"].ToString()))
        {
            SelSQL += " and m.MFGORDERNAME like '%" + dic["MfgOrdername"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["productName"].ToString()))
        {
            SelSQL += " and P2.PRODUCTNAME like '%" + dic["productName"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["productDesc"].ToString()))
        {
            SelSQL += " and P.DESCRIPTION like '%" + dic["productDesc"].ToString() + "%'";
        }
        if (!string.IsNullOrWhiteSpace(dic["containerNo"].ToString()))
        {
            SelSQL += " and sr.PRODUCTBATCHNO like '%" + dic["containerNo"].ToString() + "%'";
        }

        if (!string.IsNullOrWhiteSpace(dic["returnType"].ToString()))
        {
            SelSQL += " and sr.STOCKRETURNTYPE ='" + dic["returnType"].ToString() + "'";
        }

        if (!string.IsNullOrWhiteSpace(dic["status"].ToString()))
        {
            SelSQL += " and sr.STATUS= '" + dic["status"].ToString() + "'";
        }
        if (!string.IsNullOrWhiteSpace(dic["checkStatus"].ToString()))
        {
            SelSQL += " and sr.checkStatus= '" + dic["checkStatus"].ToString() + "'";
        }

        uMESProcessResult result = new uMESProcessResult();
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = SelSQL;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void getStockReturnApplyData(HttpContext context)
    {
        var SelSQL = GetStockReturnApplySql(context);
        if (!string.IsNullOrWhiteSpace(context.Request["mfgOrderID"].ToString()))
        {
            SelSQL += " AND sr.mfgOrderID='" + context.Request["mfgOrderID"].ToString() + "'";
        }
        SelSQL += " AND nvl(sr.STATUS,0)=0";
        var dt = DatabaseHelper.Query_ReturnDatTable(SelSQL);
        context.Response.Write(JsonConvert.SerializeObject(dt));
    }

    public string GetStockReturnApplySql(HttpContext context)
    {
        var SelSQL = @"SELECT sr.STOCKRETURNAPPLYBILLID,sr.STOCKRETURNAPPLYBILLNO,sr.STOCKRETURNTYPE,m.MFGORDERNAME,u.ATTRIBUTEVALUE MachineNO
            ,nvl(P2.PRODUCTNAME,esm.PRODUCTNAME) PRODUCTNAME,P.DESCRIPTION,sr.PRODUCTBATCHNO,sr.STOCKRETURNNUM,sr.STOCKRETURNREASON,sr.STATUS,nvl(sr.ACCEPTANCEQTY,0) ACCEPTANCEQTY
            ,to_char(sr.CREATEDATE,'yyyy-MM-dd hh24:mi:ss')CREATEDATE,e.FullNAME CREATEDATENAME
            ,to_char(sr.SUBMITDATE,'yyyy-MM-dd hh24:mi:ss')SUBMITDATE,e2.FullNAME SUBMITNAME
            ,to_char(sr.CONFIRMDATE,'yyyy-MM-dd hh24:mi:ss')CONFIRMDATE,e3.FullNAME CONFIRMNAME
            ,to_char(sr.STOCKRETURNDATE,'yyyy-MM-dd hh24:mi:ss')STOCKRETURNDATE,e4.FullNAME STOCKRETURNNAME
            ,sr.ERPSTOCKRETURNAPPLYBILLNO,sr.INSTORELOCATION, sr.WAREHOUSECODE, sr.CHECKSTATUS,to_char(m.PLANNEDSTARTDATE ,'yyyy-MM-dd')PLANNEDSTARTDATE,sr.PRODUCTID
            FROM StockReturnApplyBill sr
            LEFT JOIN MFGORDER m ON m.MFGORDERID =sr.MFGORDERID
            LEFT JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
            LEFT JOIN ERP_SEND_MATERIAL esm ON esm.ID=sr.PRODUCTID
            LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTNAME=esm.PRODUCTNAME--PRODUCTBASEID =p.PRODUCTBASEID 
            LEFT JOIN PRODUCT p ON p.PRODUCTBASEID=p2.PRODUCTBASEID --p.PRODUCTID =sr.PRODUCTID
            LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =sr.CREATEEMPLOYEEID
            LEFT JOIN EMPLOYEE e2 ON e2.EMPLOYEEID =sr.SUBMITEMPLOYEEID
            LEFT JOIN EMPLOYEE e3 ON e3.EMPLOYEEID =sr.CONFIRMEMPLOYEEID
            LEFT JOIN EMPLOYEE e4 ON e4.EMPLOYEEID =sr.STOCKRETURNEMPLOYEEID
            WHERE nvl(sr.isuse,0)=0 ";
        return SelSQL;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void updateStockReturnBillData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var type = context.Request["type"].ToString();
        var sqlArr = new ArrayList();
        var tipText = "提交";
        var updateSQL = @"Update StockReturnApplyBill set status=1,SUBMITDATE=sysdate,SUBMITEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where STOCKRETURNAPPLYBILLID='{0}'";
        if (type == "confirm") { updateSQL = @"Update StockReturnApplyBill set status=2,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where STOCKRETURNAPPLYBILLID='{0}'"; tipText = "确认"; }
        if (type == "return") { updateSQL = @"Update StockReturnApplyBill set status=1,CONFIRMDATE=sysdate,CONFIRMEMPLOYEEID='" + m_UserInfo.EmployeeID + "' where STOCKRETURNAPPLYBILLID='{0}'"; tipText = "退回"; }
        if (type == "erpno") { updateSQL = @"Update StockReturnApplyBill set ERPSTOCKRETURNAPPLYBILLNO='{0}' where STOCKRETURNAPPLYBILLID='{1}'"; tipText = "保存"; }
        foreach (DataRow row in dt.Rows)
        {
            if (type == "erpno" && row["STATUS"].ToString() == "2")
            {
                sqlArr.Add(string.Format(updateSQL, row["ERPSTOCKRETURNAPPLYBILLNO"], row["STOCKRETURNAPPLYBILLID"]));
            }
            if (type == "confirm" || type == "return" || type == "submit")
            {
                sqlArr.Add(string.Format(updateSQL, row["STOCKRETURNAPPLYBILLID"]));
            }
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? tipText + "成功" : tipText + "失败";
        if (result.Result && (tipText.Equals("确认") || tipText.Equals("退回"))) { SaveStockReturnApplyDataToWMS(dt, tipText); }
        if (result.Result && tipText.Equals("提交")) { SaveStockReturnApplyDataToQMS(dt); }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public void deleteStockReturnBillData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var sqlArr = new ArrayList();
        var updateSQL = @"Update StockReturnApplyBill set isuse=1 where STOCKRETURNAPPLYBILLID='{0}'";
        foreach (DataRow row in dt.Rows)
        {
            sqlArr.Add(string.Format(updateSQL, row["STOCKRETURNAPPLYBILLID"]));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(sqlArr);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public void GetMfgMaterial(HttpContext context) 
    {
        uMESProcessResult result = new uMESProcessResult();
        var name = context.Request["Name"].ToString();
        var mfgorderName = context.Request["mfgorderName"].ToString();
        var sql = @"SELECT ID,PRODUCTNAME NAME,PRODUCTNAME FROM erp_send_material esm WHERE esm.mfgordername ='{1}' AND esm.productname like '%{0}%'";
//        var sql = @"SELECT m.MFGORDERNAME,p.PRODUCTID ID,pbn.PRODUCTNAME||'('||p.DESCRIPTION||')' NAME,pbn.PRODUCTNAME,p.p.DESCRIPTION FROM MFGORDER m 
//            LEFT JOIN productbase mpb ON mpb.productbaseid = m.productbaseid
//            LEFT JOIN PRODUCT mp ON mp.PRODUCTID =NVL(mpb.revofrcdid, m.productid)
//            LEFT JOIN workflow wf ON wf.workflowid = mp.workflowid
//             --bom信息
//            LEFT JOIN bom b ON b.workflowid = wf.workflowid
//            LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
//            LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
//            --子零件信息
//            LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
//            LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
//            LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid 
//            WHERE --m.MFGORDERNAME ='{1}' AND 
//                pbn.PRODUCTNAME LIKE '%{0}%'
//            ORDER BY pbn.PRODUCTNAME";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql,name,mfgorderName));
        result.DBTable = dt;
        result.Result = dt.Rows.Count > 0;
        result.Message = result.Result ? "" : "订单【" + mfgorderName + "】查询不到相应的物料信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    public void GetWmsMaterialBatch(HttpContext context) 
    {
        uMESProcessResult result = new uMESProcessResult();
        var paraDic = JsonConvert.DeserializeObject<Dictionary<string,string>>(context.Request["data"].ToString());
        var name = paraDic["Name"].ToString();
        var mfgorderName = paraDic["mfgorderName"].ToString();
        var sql = @"SELECT esm.productbatchno,esm.lgort,esm.uom,esm.qty,esm.rsnum FROM erp_send_material esm WHERE  esm.productname ='{0}' AND esm.mfgordername ='{1}'";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, name, mfgorderName));
        result.DBTable = dt;
        result.Result = dt.Rows.Count > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    

    void SaveStockReturnApplyDataToWMS(DataTable dt,string type)
    {
        DataView dv = dt.DefaultView;
        DataTable dt2 = dv.ToTable(true, "mfgordername", "warehouseCode", "stockreturntype", "instorelocation");
        foreach (DataRow row in dt2.Rows)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("warehouseCode", row["warehouseCode"]);//仓库代码
            dic.Add("companyCode", "LYDL");//货主代码
            dic.Add("bizDataType", row["stockreturntype"]);//业务类型
            dic.Add("bizDataNo", row["mfgordername"]);//生产订单号
            dic.Add("docNo", "业务流水号");//业务流水号--?????
            dic.Add("supplierCode", m_UserInfo.FactoryCode);//供应商ID
            dic.Add("storageLocation", row["instorelocation"]);//库存地点
            dic.Add("rtdDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//退库日期(提交日期)
            dic.Add("status", type.Equals("确认")?0:1);//0：申请;1:撤销
            for (var i = 1; i <= 10; i++)
            {
                dic.Add(String.Format("userDef{0}", i.ToString().PadLeft(2, '0')), ""); //预留字段
            }
            DataTable dt3 = dt.Select(string.Format("warehouseCode='{0}' and stockreturntype='{1}' and instorelocation='{2}'", row["warehouseCode"], row["stockreturntype"], row["instorelocation"])).CopyToDataTable();
            var dicList = new List<Dictionary<string, object>>();
            var lineNo = 1;
            foreach (DataRow row2 in dt3.Rows)
            {
                Dictionary<string, object> dicD = new Dictionary<string, object>();
                dicD.Add("lineNo", lineNo);//业务流水行项目号(必填)
                dicD.Add("itemCode", row2["productname"]);//物料编码(必填)
                dicD.Add("itemName", row2["description"]);//物料名称（描述）(必填)
                dicD.Add("modelSpecs", "");//规格型号
                dicD.Add("unit", "");//计量单位
                dicD.Add("qty", row2["stockreturnnum"]);//数量(必填)
                dicD.Add("sapBatch", "SAP批次");//SAP批次(必填)--?????
                dicD.Add("mdfBatch", "生产批次");//生产批次--?????
                dicD.Add("heatBatch", "");//炉批号
                dicD.Add("serialCode", row2["productbatchno"]);//序列号
                dicD.Add("supplierCode", "321");//供应商编号(必填)????
                dicD.Add("supplierName", "");//供应商名称
                dicD.Add("suitableModel", "");//适用机型

                dicD.Add("qirStatus", "");//检验状态
                dicD.Add("revisionLevel", "01");//设计版次(必填)----???
                dicD.Add("mdfDate", row2["PLANNEDSTARTDATE"]);//生产日期(必填)
                dicD.Add("preservationDate", "");//油封日期
                dicD.Add("accompanyingDocs", "");//随带文件
                dicD.Add("coCNumber", "");//合格证编号
                dicD.Add("specialInv", "");//特殊库存
                dicD.Add("invType", "");//库存类型

                dicD.Add("restrictions", "");//限制信息
                dicD.Add("applicableScope", "");//使用范围
                dicD.Add("remarks", "");//备注
                for (var i = 1; i <= 10; i++)
                {
                    dicD.Add(String.Format("userDef{0}", i.ToString().PadLeft(2, '0')), ""); //预留字段
                }
                dicList.Add(dicD);
                lineNo++;
            }
            dic.Add("itemList", dicList);
            
            //----------插入推送表---------------'
            string jsonStr = JsonConvert.SerializeObject(dic); //将对象转换成JSON
            var insertSql = new StringBuilder();
            insertSql.Append(@"INSERT INTO sync_sendto_wms(json,methodname,toappid,tablename,uniquecolname,uniquecolvalue,create_emp)VALUES(");
            insertSql.AppendFormat("'{0}',", jsonStr); //json
            insertSql.AppendFormat("'{0}',", "退料退库"+(type.Equals("确认")?"申请":"撤销")); //推送方法名
            insertSql.AppendFormat("'{0}',", toAppID_WMS); //推送目标ID
            insertSql.AppendFormat("'{0}',", "mfgorder".ToUpper()); //推送对应表
            insertSql.AppendFormat("'{0}',", "mfgordername".ToUpper()); //推送对应表列明
            insertSql.AppendFormat("'{0}',", row["mfgordername"]); //推送对应表列值
            insertSql.AppendFormat("'{0}')", m_UserInfo.EmployeeID); //创建人
            DatabaseHelper.ExecuteSql(insertSql.ToString());
        }
    }

    void SaveStockReturnApplyDataToQMS(DataTable dt) 
    {
        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
        doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
        System.Xml.XmlNode ProcesssNode = doc.CreateElement("QIS_PROCESSs");
        System.Xml.XmlNode nodeT = doc.CreateElement("TASK_TYPE");//任务类型
        nodeT.InnerText = "退库检验";
        ProcesssNode.AppendChild(nodeT);
        foreach (DataRow dr in dt.Rows)
        {
            System.Xml.XmlNode ProcessNode = doc.CreateElement("QIS_PROCESS");
            System.Xml.XmlNode node = doc.CreateElement("ORDER_NO");//订单编号
            node.AppendChild(doc.CreateCDataSection(dr["mfgordername"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_CODE");//产品件号
            node.AppendChild(doc.CreateCDataSection(dr["productname"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_NAME");//产品名称
            node.AppendChild(doc.CreateCDataSection(dr["description"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("PRODUCT_BATCH");//批次号
            node.AppendChild(doc.CreateCDataSection(dr["productbatchno"].ToString()));
            ProcessNode.AppendChild(node);

            node = doc.CreateElement("CHECK_NUM");//交检数量
            node.AppendChild(doc.CreateCDataSection(dr["stockreturnnum"].ToString()));
            ProcessNode.AppendChild(node);
            ProcesssNode.AppendChild(ProcessNode);
        }
        doc.AppendChild(ProcesssNode);
        string xmlStr = doc.InnerXml;
        //----------插入推送表---------------'
        var insertSQL = @"INSERT INTO WRITETOOTHERSYSTEM(writetoothersystemid,parentid,recordtype,sendxml)values(sys_guid(),'{0}','qms_StockReturnApply','{1}')";
        DatabaseHelper.ExecuteSql(string.Format(insertSQL, dt.Rows[0]["mfgordername"].ToString(), xmlStr));
    }


}